﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using WinFormsApp1.RelationForms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace WinFormsApp1
{
    public partial class FormRelationMap : Form
    {
        private List<TableWithKey> m_tables;
        private List<DataColumInfo> m_allColumns;
        private List<DataColumInfo> m_unUsedColumns;
        private Dictionary<string, bool> m_isTableShow = new Dictionary<string, bool>();

        #region 1、构造函数
        public FormRelationMap(List<TableWithKey> _tables)
        {
            m_tables = _tables;
            InitializeComponent();
        }

        private void FormRelationMap_Load(object sender, EventArgs e)
        {
            var columns = GetAllColumns();
            m_allColumns = columns;

            m_unUsedColumns = new List<DataColumInfo>();
            m_unUsedColumns.AddRange(columns.ToArray());
            columns.Sort(new DataColumInfoComparerTNC());

            for (var i = 0; i < columns.Count; i++)
            {
                if (m_isTableShow.ContainsKey(columns[i].TableName) == false)
                    m_isTableShow.Add(columns[i].TableName, true);
            }

            BuildColumnList();
        }

        private void BuildColumnList()
        {
            var columns = m_allColumns;
            this.listView1.Items.Clear();
            for (var i = 0; i < columns.Count; i++)
            {
                if (m_isTableShow[columns[i].TableName] == false)
                {
                    continue;
                }
                ListViewItem lvi = new ListViewItem(columns[i].TableName);
                lvi.SubItems.Add(columns[i].ColumnName);
                lvi.SubItems.Add(columns[i].ColumnType.ToString());
                lvi.SubItems.Add(columns[i].ColumnLength.ToString());
                lvi.Tag = columns[i];

                this.listView1.Items.Add(lvi);
            }
        }

        private List<DataColumInfo> GetAllColumns()
        {
            List<DataColumInfo> columns = new List<DataColumInfo>();
            for (var i = 0; i < m_tables.Count; i++)
            {
                columns.AddRange(m_tables[i].TableData.Columns);
            }
            return columns;
        }
        #endregion

        #region 1.1、过滤关系
        private void 过滤ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            FormRelationMapFilter form = new FormRelationMapFilter();
            form.AllTables = m_isTableShow;
            form.StartPosition = FormStartPosition.CenterScreen;
            if (form.ShowDialog() == DialogResult.OK)
            {
                BuildColumnList();
            }
        }

        #region 2、查询关系数据
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            List<DataColumInfo> selectColumns = new List<DataColumInfo>();
            for (var i = 0; i < this.listView1.SelectedItems.Count; i++)
            {
                selectColumns.Add(this.listView1.SelectedItems[i].Tag as DataColumInfo);
            }
            ShowRelationData(selectColumns);
        }
        private void ShowRelationData(List<DataColumInfo> selectColumns)
        {
            DataTable dataTable = new DataTable();
            for (var i = 0; i < selectColumns.Count; i++)
            {
                dataTable.Columns.Add(selectColumns[i].TableName + "_" + selectColumns[i].ColumnName);
            }

            List<_stringColumn> items = new List<_stringColumn>();
            for (var i = 0; i < 20; i++)
            {
                List<object> list = new List<object>();
                for (var j = 0; j < selectColumns.Count; j++)
                {
                    var rows = selectColumns[j].RefExcel.RefDataTable.Rows;
                    if (rows.Count <= i) { list.Add(""); continue; }
                    if (rows[i][selectColumns[j].ColumnName] == null)
                    {
                        list.Add("");
                        continue;
                    }
                    var str = rows[i][selectColumns[j].ColumnName].ToString();
                    list.Add(str);
                    if (string.IsNullOrEmpty(str) == false)
                    {
                        items.Add(new _stringColumn()
                        {
                            Str = str,
                            ColumnIndex = j,
                        });
                    }
                }
                dataTable.Rows.Add(list.ToArray());
            }
            this.dataGridView1.DataSource = dataTable;
            items.Sort(new _stringColumnCmp());

            this.labelRelation.Text = "结论：多列【不】相同数据，可能【不】存在关联关系";
            for (var i = items.Count - 1; i > 0; i--)
            {
                if (items[i].Str == items[i - 1].Str && items[i].ColumnIndex != items[i - 1].ColumnIndex)
                {
                    this.labelRelation.Text = "结论：多列【存在】相同数据，可能存在关联关系";
                    break;
                }
            }
        }
        #endregion

        #endregion

        #region 3、建立关系
        private void 根据名称长度建立关系ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.treeView1.Nodes.Clear();

            m_unUsedColumns.Sort(new DataColumInfoComparerNL());

            var lastColumn = m_unUsedColumns[m_unUsedColumns.Count - 1];

            TreeNode lastTreeNode = new TreeNode("NL-" + lastColumn.ColumnName + "-" + lastColumn.ColumnLength);
            lastTreeNode.Tag = "关系";

            treeView1.Nodes.Add(lastTreeNode);

            TreeNode childNode1 = AppendEntityNames(lastColumn);
            lastTreeNode.Nodes.Add(childNode1);


            bool lastTreeNodeAdded = false;

            for (var i = m_unUsedColumns.Count - 2; i >= 0; i--)
            {
                var currntColumn = m_unUsedColumns[i];
                if (m_isTableShow[currntColumn.TableName] == false)
                {
                    continue;
                }

                if (lastColumn.ColumnName == currntColumn.ColumnName && lastColumn.ColumnLength == currntColumn.ColumnLength)
                {
                    TreeNode childNode2 = AppendEntityNames(currntColumn);
                    lastTreeNode.Nodes.Insert(0, childNode2);
                    if (lastTreeNodeAdded == false && lastColumn.ColumnLength > 0)
                    {
                        lastTreeNodeAdded = true;
                        treeView1.Nodes.Add(lastTreeNode);
                    }
                }
                else
                {
                    lastColumn = currntColumn;
                    lastTreeNode = new TreeNode("NL-" + lastColumn.ColumnName + "-" + lastColumn.ColumnLength);
                    lastTreeNode.Tag = "关系";

                    childNode1 = AppendEntityNames(lastColumn);
                    lastTreeNode.Nodes.Add(childNode1);
                    lastTreeNodeAdded = false;
                }
            }
        }
        private TreeNode AppendEntityNames(DataColumInfo lastColumn)
        {
            TreeNode childNode1 = new TreeNode(lastColumn.TableName);
            childNode1.Tag = lastColumn;
            for (var i = 0; i < lastColumn.RefExcel.EntityColumns.Count; i++)
            {
                var ec = lastColumn.RefExcel.EntityColumns[i];
                TreeNode entityNameNode = new TreeNode(ec.ColumnName);
                childNode1.Nodes.Add(entityNameNode);
            }

            return childNode1;
        }
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode treeNode = e.Node as TreeNode;
            var nodes = new List<DataColumInfo>();
            if (treeNode.Tag == "关系")
            {
                //属于总节点
                for (var i = 0; i < treeNode.Nodes.Count; i++)
                {
                    var node = treeNode.Nodes[i];
                    nodes.Add(node.Tag as DataColumInfo);
                }
            }
            else
            {
                nodes.Add(treeNode.Tag as DataColumInfo);
                this.propertyGrid1.SelectedObject = treeNode.Tag as DataColumInfo;
            }
            ShowRelationData(nodes);
        }
        #endregion

        #region 4、预览关系
        private void 查询关系ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.treeView1.SelectedNode == null) return;
            if (this.treeView1.SelectedNode.Tag != "关系") return;

            var treeNode = this.treeView1.SelectedNode;

            var nodes = new List<DataColumInfo>();
            for (var i = 0; i < treeNode.Nodes.Count; i++)
            {
                var node = treeNode.Nodes[i];
                nodes.Add(node.Tag as DataColumInfo);
            }

            FormRelationPreview form = new FormRelationPreview(nodes);
            form.Text = "关系预览  " + this.treeView1.SelectedNode.Text;
            form.StartPosition = FormStartPosition.CenterScreen;
            form.Show();
        }
        #endregion

        #region 5、建立单表关系
        private void 建立单表关系ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormRelationOneTable form=new FormRelationOneTable()
            {
                AllTables= m_tables
            };
            form.StartPosition=FormStartPosition.CenterScreen;
            form.Show(this);
        } 
        #endregion
    }
    class _stringColumn
    {
        public string Str;
        public int ColumnIndex;
    }
    class _stringColumnCmp : IComparer<_stringColumn>
    {
        public int Compare(_stringColumn? x, _stringColumn? y)
        {
            var t = x.Str.CompareTo(y.Str);
            if (t != 0) return t;
            return x.ColumnIndex.CompareTo(y.ColumnIndex);
        }
    }
}
